package com.weayer.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weayer.constant.CommonStatusEnum;
import com.weayer.constant.IdentityConstants;
import com.weayer.constant.OrderInfoConstants;
import com.weayer.dto.Car;
import com.weayer.dto.OrderInfo;
import com.weayer.dto.PriceRule;
import com.weayer.dto.ResponseResult;
import com.weayer.mapper.OrderInfoMapper;
import com.weayer.remote.ServiceDriverUserClient;
import com.weayer.remote.ServiceMapClient;
import com.weayer.remote.ServicePriceClient;
import com.weayer.remote.ServiceSsePushClient;

import com.weayer.request.DriverGrabRequest;
import com.weayer.request.OrderRequest;
import com.weayer.request.PushRequest;
import com.weayer.response.OrderDriverResponse;
import com.weayer.response.SearchTerminalResponse;
import com.weayer.response.TrsearchResponse;
import com.weayer.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description: Service服务 - 订单 - 订单Service
 * @author: Weayer
 **/
@Service
@Slf4j
public class OrderInfoService{
    @Autowired
    OrderInfoMapper orderInfoMapper;
    @Autowired
    ServicePriceClient servicePriceClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ServiceDriverUserClient serviceDriverUserClient;
    @Autowired
    ServiceMapClient serviceMapClient;
    @Autowired
    @Qualifier("redissonBootClient")
    RedissonClient redissonClient;
    @Autowired
    ServiceSsePushClient serviceSsePushClient;

    /**
     * @Description: 创建实时订单
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult add(OrderRequest orderRequest){
        // 当前城市存在司机
        ResponseResult<Boolean> responseResult1 = serviceDriverUserClient.isAvailableDriver(orderRequest.getAddress());
        if(!responseResult1.getData()){
            return ResponseResult.fail(CommonStatusEnum.CITY_DRIVER_NOT_AVAILABLE.getCode(), CommonStatusEnum.CITY_DRIVER_NOT_AVAILABLE.getValue());
        }
        // 黑名单校验
        String deviceCode = orderRequest.getDeviceCode();
        String deviceCodeKey = RedisPrefixUtils.blackDeviceCodePrefix + deviceCode;
        if(stringRedisTemplate.hasKey(deviceCodeKey)){
            int count = Integer.parseInt(stringRedisTemplate.opsForValue().get(deviceCodeKey));
            if(count >= 2){  // 设为黑名单
                return ResponseResult.fail(CommonStatusEnum.DEVICE_IS_BLACK.getCode(), CommonStatusEnum.DEVICE_IS_BLACK.getValue());
            }else{      // 次数+1
                stringRedisTemplate.opsForValue().increment(deviceCodeKey);
            }
        }else{
            stringRedisTemplate.opsForValue().setIfAbsent(deviceCodeKey, "1", 1L, TimeUnit.HOURS);
        }
        // 当前计价规则存在（根据城市代码、车辆类型）
        String fareType = orderRequest.getFareType();
        int index = fareType.indexOf("$");
        PriceRule priceRule = new PriceRule();
        priceRule.setCityCode(fareType.substring(0, index));
        priceRule.setVehicleType(fareType.substring(index + 1));
        ResponseResult<Boolean> responseResult2 = servicePriceClient.ifExists(priceRule);
        if(!responseResult2.getData()){
            return ResponseResult.fail(CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getCode(), CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getValue());
        }
        // 当前计价规则的版本必须最新
        ResponseResult<Boolean> responseResult3 = servicePriceClient.isNewest(orderRequest.getFareType(), orderRequest.getFareVersion());
        if(responseResult3.getCode() == CommonStatusEnum.PRICE_RULE_EMPTY.getCode()){
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EMPTY.getCode(), CommonStatusEnum.PRICE_RULE_EMPTY.getValue());
        }
        if(!responseResult3.getData()){
            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_NEED_CHANGE.getCode(), CommonStatusEnum.PRICE_RULE_NEED_CHANGE.getValue());
        }
        // 如果当前乘客有正在进行的订单(订单状态1~7)，不允许重复下单
        int validOrderNumber = isPassengerOrderGoing(orderRequest.getPassengerId());
        if(validOrderNumber > 0){
            return ResponseResult.fail(CommonStatusEnum.ORDER_CAN_NOT_CREATE.getCode(), CommonStatusEnum.ORDER_CAN_NOT_CREATE.getValue());
        }
        // 创建订单
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderRequest, orderInfo);
        orderInfo.setOrderStatus(OrderInfoConstants.ORDER_START);
        LocalDateTime now = LocalDateTime.now();
        orderInfo.setGmtCreate(now);
        orderInfo.setGmtModified(now);

        orderInfoMapper.insert(orderInfo);
        // 定时监听系统派单
        for(int i = 0; i < 5; ++i){
            boolean result = dispatchRealTimeOrder(orderInfo);
            if (result){
                break;
            }
            if(i == 4){
                // 订单无效
                orderInfo.setOrderStatus(OrderInfoConstants.ORDER_INVALID);
            }else{
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseResult.success();
    }

    /**
     * @Description: 创建预约订单
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult book(OrderRequest orderRequest){
//        // 当前城市存在司机
//        ResponseResult<Boolean> responseResult1 = serviceDriverUserClient.isAvailableDriver(orderRequest.getAddress());
//        if(!responseResult1.getData()){
//            return ResponseResult.fail(CommonStatusEnum.CITY_DRIVER_NOT_AVAILABLE.getCode(), CommonStatusEnum.CITY_DRIVER_NOT_AVAILABLE.getValue());
//        }
//        // 黑名单校验
//        String deviceCode = orderRequest.getDeviceCode();
//        String deviceCodeKey = RedisPrefixUtils.blackDeviceCodePrefix + deviceCode;
//        if(stringRedisTemplate.hasKey(deviceCodeKey)){
//            int count = Integer.parseInt(stringRedisTemplate.opsForValue().get(deviceCodeKey));
//            if(count >= 2){  // 设为黑名单
//                return ResponseResult.fail(CommonStatusEnum.DEVICE_IS_BLACK.getCode(), CommonStatusEnum.DEVICE_IS_BLACK.getValue());
//            }else{      // 次数+1
//                stringRedisTemplate.opsForValue().increment(deviceCodeKey);
//            }
//        }else{
//            stringRedisTemplate.opsForValue().setIfAbsent(deviceCodeKey, "1", 1L, TimeUnit.HOURS);
//        }
//        // 当前计价规则存在（根据城市代码、车辆类型）
//        String fareType = orderRequest.getFareType();
//        int index = fareType.indexOf("$");
//        PriceRule priceRule = new PriceRule();
//        priceRule.setCityCode(fareType.substring(0, index));
//        priceRule.setVehicleType(fareType.substring(index + 1));
//        ResponseResult<Boolean> responseResult2 = servicePriceClient.ifExists(priceRule);
//        if(!responseResult2.getData()){
//            return ResponseResult.fail(CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getCode(), CommonStatusEnum.CITY_SERVICE_NOT_SERVICE.getValue());
//        }
//        // 当前计价规则的版本必须最新
//        ResponseResult<Boolean> responseResult3 = servicePriceClient.isNewest(orderRequest.getFareType(), orderRequest.getFareVersion());
//        if(responseResult3.getCode() == CommonStatusEnum.PRICE_RULE_EMPTY.getCode()){
//            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_EMPTY.getCode(), CommonStatusEnum.PRICE_RULE_EMPTY.getValue());
//        }
//        if(!responseResult3.getData()){
//            return ResponseResult.fail(CommonStatusEnum.PRICE_RULE_NEED_CHANGE.getCode(), CommonStatusEnum.PRICE_RULE_NEED_CHANGE.getValue());
//        }
//        // 如果当前乘客有正在进行的订单(订单状态1~7)，不允许重复下单
//        int validOrderNumber = isPassengerOrderGoing(orderRequest.getPassengerId());
//        if(validOrderNumber > 0){
//            return ResponseResult.fail(CommonStatusEnum.ORDER_CAN_NOT_CREATE.getCode(), CommonStatusEnum.ORDER_CAN_NOT_CREATE.getValue());
//        }
        // 创建订单
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderRequest, orderInfo);
        orderInfo.setOrderStatus(OrderInfoConstants.ORDER_START);
        LocalDateTime now = LocalDateTime.now();
        orderInfo.setGmtCreate(now);
        orderInfo.setGmtModified(now);

        orderInfoMapper.insert(orderInfo);
        // 定时监听系统派单
        for(int i = 0; i < 5; ++i){
            boolean result = dispatchBookOrder(orderInfo);
            if (result){
                break;
            }
            if(i == 4){
                // 订单无效
                orderInfo.setOrderStatus(OrderInfoConstants.ORDER_INVALID);
            }else{
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseResult.success();
    }

    /**
     * @Description: 查询当前乘客正在进行的订单
     * @Param: [passengerId]
     * @return: int
     **/
    public int isPassengerOrderGoing(Long passengerId){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("passenger_id", passengerId);
        queryWrapper.and(wrapper->wrapper.eq("order_status", OrderInfoConstants.ORDER_START)
                .or().eq("order_status", OrderInfoConstants.DRIVER_RECEIVE_ORDER)
                .or().eq("order_status", OrderInfoConstants.DRIVER_PICK_UP_PASSENGER)
                .or().eq("order_status", OrderInfoConstants.DRIVER_ARRIVED_DEPARTURE)
                .or().eq("order_status", OrderInfoConstants.PASSENGER_GET_ON)
                .or().eq("order_status", OrderInfoConstants.PASSENGER_GET_OFF)
                .or().eq("order_status", OrderInfoConstants.PAYING_START));
        return orderInfoMapper.selectCount(queryWrapper);
    }
    /**
     * @Description: 查询当前司机正在进行的订单
     * @Param: [driverId]
     * @return: int
     **/
    public int isDriverOrderGoing(Long driverId){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("driver_id", driverId);
        queryWrapper.and(wrapper->wrapper.eq("order_status", OrderInfoConstants.DRIVER_RECEIVE_ORDER)
                .or().eq("order_status", OrderInfoConstants.DRIVER_PICK_UP_PASSENGER)
                .or().eq("order_status", OrderInfoConstants.DRIVER_ARRIVED_DEPARTURE)
                .or().eq("order_status", OrderInfoConstants.PASSENGER_GET_ON));
        return orderInfoMapper.selectCount(queryWrapper);
    }
    /**
     * @Description: 派送实时订单
     * @Param: [orderInfo]
     * @return: void
     **/
    public boolean dispatchRealTimeOrder(OrderInfo orderInfo){
        String depLatitude = orderInfo.getDepLatitude();
        String depLongitude = orderInfo.getDepLongitude();
        String center = depLatitude + "," + depLongitude;
        List<Integer> radiusList = new ArrayList<>();
        radiusList.add(500);
        radiusList.add(1000);
        radiusList.add(2000);
        ResponseResult<List<SearchTerminalResponse>> listResponseResult = null;
        boolean flag = false;   // 搜索成功标记
        for(int i = 0; i < radiusList.size(); ++i){
            if(flag){   // 派单成功，退出循环
                break;
            }
            // 终端搜索，获取终端
            listResponseResult = serviceMapClient.search(center, radiusList.get(i));
            log.info("搜索范围: " + radiusList.get(i));
            if(CollectionUtils.isEmpty(listResponseResult.getData())){
                continue;
            }
            // 解析终端，查询车辆信息
            for(SearchTerminalResponse terminalResponse : listResponseResult.getData()){
                log.info("终端id: {}, 车辆id: {}", terminalResponse.getTid(), terminalResponse.getCarId());
                Long carId = terminalResponse.getCarId();
                // 查询司机是否可以工作
                ResponseResult<OrderDriverResponse> orderDriverResponse = serviceDriverUserClient.getAvailableDriver(carId);
                if(orderDriverResponse.getCode() == CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode()){
                    log.info("该车辆司机无法工作");
                }else{
                    Long driverId = orderDriverResponse.getData().getDriverId();
                    synchronized ((driverId + "").intern()) {     // 单机解决并发问题
                        String lockKey = driverId + "";
                        RLock lock = redissonClient.getLock(lockKey);    // 分布式锁redisson
                        lock.lock();
                        // 查询当前司机正在进行的订单
                        int validDriverNumber = isDriverOrderGoing(driverId);
                        if (validDriverNumber > 0) {
                            lock.unlock();
                            log.info("该车辆司机无法派单");
                            continue;
                        }
                        flag = true;
                        log.info("该车辆司机可以派单");
                        // 找到符合车辆 - 强制给司机实时派单
                        orderInfo.setDriverId(driverId);
                        orderInfo.setDriverPhone(orderDriverResponse.getData().getDriverPhone());
                        orderInfo.setCarId(orderDriverResponse.getData().getCarId());
                        orderInfo.setReceiveOrderCarLongitude(terminalResponse.getLongitude());
                        orderInfo.setReceiveOrderCarLatitude(terminalResponse.getLatitude());
                        orderInfo.setReceiveOrderTime(LocalDateTime.now());
                        orderInfo.setLicenseId(orderDriverResponse.getData().getLicenseId());
                        orderInfo.setVehicleNo(orderDriverResponse.getData().getVehicleNo());
                        orderInfo.setOrderStatus(OrderInfoConstants.DRIVER_RECEIVE_ORDER);
                        orderInfoMapper.updateById(orderInfo);
                        // 通知司机
                        JSONObject driverContent = new JSONObject();
                        driverContent.put("passengerId", orderInfo.getPassengerId());
                        driverContent.put("passengerPhone", orderInfo.getPassengerPhone());
                        driverContent.put("departure", orderInfo.getDeparture());
                        driverContent.put("depLongitude", orderInfo.getDepLongitude());
                        driverContent.put("depLatitude", orderInfo.getDepLatitude());
                        driverContent.put("destination", orderInfo.getDestination());
                        driverContent.put("destLongitude", orderInfo.getDestLongitude());
                        driverContent.put("destLatitude", orderInfo.getDestLatitude());
                        PushRequest pushRequest1 = new PushRequest(driverId, IdentityConstants.DRIVER_IDENTITY, driverContent.toString());
                        serviceSsePushClient.push(pushRequest1);
                        // 通知乘客
                        JSONObject passengerContent = new JSONObject();
                        passengerContent.put("driverId", orderInfo.getDriverId());
                        passengerContent.put("driverPhone", orderInfo.getDriverPhone());
                        passengerContent.put("vehicleNo", orderInfo.getVehicleNo());
                        ResponseResult<Car> carResponseResult = serviceDriverUserClient.getCarById(orderInfo.getCarId());
                        passengerContent.put("brand", carResponseResult.getData().getBrand());
                        passengerContent.put("model", carResponseResult.getData().getModel());
                        passengerContent.put("vehicleColor", carResponseResult.getData().getVehicleColor());
                        passengerContent.put("receiveOrderCarLongitude", orderInfo.getReceiveOrderCarLongitude());
                        passengerContent.put("receiveOrderCarLatitude", orderInfo.getReceiveOrderCarLatitude());
                        PushRequest pushRequest2 = new PushRequest(orderInfo.getPassengerId(), IdentityConstants.PASSENGER_IDENTITY, passengerContent.toString());
                        serviceSsePushClient.push(pushRequest2);
                        lock.unlock();
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     * @Description: 派送预约订单
     * @Param: [orderInfo]
     * @return: boolean
     **/
    public boolean dispatchBookOrder(OrderInfo orderInfo){
        String depLatitude = orderInfo.getDepLatitude();
        String depLongitude = orderInfo.getDepLongitude();
        String center = depLatitude + "," + depLongitude;
        List<Integer> radiusList = new ArrayList<>();
        radiusList.add(500);
        radiusList.add(1000);
        radiusList.add(2000);
        ResponseResult<List<SearchTerminalResponse>> listResponseResult = null;
        boolean flag = false;   // 搜索成功标记
        for(int i = 0; i < radiusList.size(); ++i){
            if(flag){   // 派单成功，退出循环
                break;
            }
            // 终端搜索，获取终端
            listResponseResult = serviceMapClient.search(center, radiusList.get(i));
            log.info("搜索范围: " + radiusList.get(i));
            if(CollectionUtils.isEmpty(listResponseResult.getData())){
                continue;
            }
            // 解析终端，查询车辆信息
            for(SearchTerminalResponse terminalResponse : listResponseResult.getData()){
                log.info("终端id: {}, 车辆id: {}", terminalResponse.getTid(), terminalResponse.getCarId());
                Long carId = terminalResponse.getCarId();
                // 查询司机是否可以工作
                ResponseResult<OrderDriverResponse> orderDriverResponse = serviceDriverUserClient.getAvailableDriver(carId);
                if(orderDriverResponse.getCode() == CommonStatusEnum.AVAILABLE_DRIVER_EMPTY.getCode()){
                    log.info("该车辆司机无法工作");
                }else{
                    Long driverId = orderDriverResponse.getData().getDriverId();
                    // 查询当前司机正在进行的订单
                    int validDriverNumber = isDriverOrderGoing(driverId);
                    if (validDriverNumber > 0) {
                        log.info("该车辆司机无法派单");
                        continue;
                    }
                    flag = true;
                    log.info("该车辆司机可以派单");

                    // 通知司机
                    JSONObject driverContent = new JSONObject();
                    driverContent.put("passengerId", orderInfo.getPassengerId());
                    driverContent.put("passengerPhone", orderInfo.getPassengerPhone());
                    driverContent.put("departure", orderInfo.getDeparture());
                    driverContent.put("depLongitude", orderInfo.getDepLongitude());
                    driverContent.put("depLatitude", orderInfo.getDepLatitude());
                    driverContent.put("destination", orderInfo.getDestination());
                    driverContent.put("destLongitude", orderInfo.getDestLongitude());
                    driverContent.put("destLatitude", orderInfo.getDestLatitude());
                    PushRequest pushRequest1 = new PushRequest(driverId, IdentityConstants.DRIVER_IDENTITY, driverContent.toString());
                    serviceSsePushClient.push(pushRequest1);
//                    // 通知乘客
//                    JSONObject passengerContent = new JSONObject();
//                    passengerContent.put("driverId", orderInfo.getDriverId());
//                    passengerContent.put("driverPhone", orderInfo.getDriverPhone());
//                    passengerContent.put("vehicleNo", orderInfo.getVehicleNo());
//                    ResponseResult<Car> carResponseResult = serviceDriverUserClient.getCarById(orderInfo.getCarId());
//                    passengerContent.put("brand", carResponseResult.getData().getBrand());
//                    passengerContent.put("model", carResponseResult.getData().getModel());
//                    passengerContent.put("vehicleColor", carResponseResult.getData().getVehicleColor());
//                    passengerContent.put("receiveOrderCarLongitude", orderInfo.getReceiveOrderCarLongitude());
//                    passengerContent.put("receiveOrderCarLatitude", orderInfo.getReceiveOrderCarLatitude());
//                    PushRequest pushRequest2 = new PushRequest(orderInfo.getPassengerId(), IdentityConstants.PASSENGER_IDENTITY, passengerContent.toString());
//                    serviceSsePushClient.push(pushRequest2);
                    break;
                    }
                }
            }
        return flag;
    }

    /**
     * @Description: 司机抢单
     * @Param: [driverGrabRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {
        // 获取 orderId
        Long orderId = driverGrabRequest.getOrderId();
        // 对于同步的方法加锁，原则：尽可能缩小锁的范围
//        synchronized (this){
//        synchronized ((orderId + "").intern()){
            // 查询订单
            OrderInfo orderInfo =  orderInfoMapper.selectById(orderId);
            if(orderInfo == null){
                return ResponseResult.fail(CommonStatusEnum.ORDER_NOT_EXISTS.getCode(), CommonStatusEnum.ORDER_NOT_EXISTS.getValue());
            }
            int orderStatus = orderInfo.getOrderStatus();
            if(orderStatus != OrderInfoConstants.ORDER_START){
                return ResponseResult.fail(CommonStatusEnum.ORDER_CAN_NOT_GRAB.getCode(), CommonStatusEnum.ORDER_CAN_NOT_GRAB.getValue());
            }

            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 更新订单
            Long driverId = driverGrabRequest.getDriverId();
            Long carId = driverGrabRequest.getCarId();
            String licenseId = driverGrabRequest.getLicenseId();
            String vehicleNo = driverGrabRequest.getVehicleNo();
            String receiveOrderCarLatitude = driverGrabRequest.getReceiveOrderCarLatitude();
            String receiveOrderCarLongitude = driverGrabRequest.getReceiveOrderCarLongitude();
            String vehicleType = driverGrabRequest.getVehicleType();
            String driverPhone = driverGrabRequest.getDriverPhone();
            orderInfo.setDriverId(driverId);
            orderInfo.setDriverPhone(driverPhone);
            orderInfo.setCarId(carId);
            orderInfo.setReceiveOrderCarLongitude(receiveOrderCarLongitude);
            orderInfo.setReceiveOrderCarLatitude(receiveOrderCarLatitude);
            orderInfo.setReceiveOrderTime(LocalDateTime.now());
            orderInfo.setLicenseId(licenseId);
            orderInfo.setVehicleNo(vehicleNo);
            orderInfo.setVehicleType(vehicleType);
            orderInfo.setOrderStatus(OrderInfoConstants.DRIVER_RECEIVE_ORDER);
            orderInfoMapper.updateById(orderInfo);

//        }

        return  ResponseResult.success();
    }

    /**
     * @Description: 司机去接乘客
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult toPickUpPassenger(OrderRequest orderRequest){
        Long orderId = orderRequest.getOrderId();
        LocalDateTime toPickUpPassengerTime = orderRequest.getToPickUpPassengerTime();
        String toPickUpPassengerLongitude = orderRequest.getToPickUpPassengerLongitude();
        String toPickUpPassengerLatitude = orderRequest.getToPickUpPassengerLatitude();
        String toPickUpPassengerAddress = orderRequest.getToPickUpPassengerAddress();
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        orderInfo.setToPickUpPassengerAddress(toPickUpPassengerAddress);
        orderInfo.setToPickUpPassengerLatitude(toPickUpPassengerLatitude);
        orderInfo.setToPickUpPassengerLongitude(toPickUpPassengerLongitude);
        orderInfo.setToPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setOrderStatus(OrderInfoConstants.DRIVER_PICK_UP_PASSENGER);

        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    /**
     * @Description: 司机到达乘客上车点
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult arrivedDeparture(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",orderId);

        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        orderInfo.setOrderStatus(OrderInfoConstants.DRIVER_ARRIVED_DEPARTURE);

        orderInfo.setDriverArrivedDepartureTime(LocalDateTime.now());
        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    /**
     * @Description: 司机接到乘客，乘客上车
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult pickUpPassenger(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        orderInfo.setPickUpPassengerLongitude(orderRequest.getPickUpPassengerLongitude());
        orderInfo.setPickUpPassengerLatitude(orderRequest.getPickUpPassengerLatitude());
        orderInfo.setPickUpPassengerTime(LocalDateTime.now());
        orderInfo.setOrderStatus(OrderInfoConstants.PASSENGER_GET_ON);

        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    /**
     * @Description: 乘客到达目的地，行程终止
     * @Param: [orderRequest]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult passengerGetoff(OrderRequest orderRequest) {
        Long orderId = orderRequest.getOrderId();

        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",orderId);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);

        orderInfo.setPassengerGetoffTime(LocalDateTime.now());
        orderInfo.setPassengerGetoffLongitude(orderRequest.getPassengerGetoffLongitude());
        orderInfo.setPassengerGetoffLatitude(orderRequest.getPassengerGetoffLatitude());
        orderInfo.setOrderStatus(OrderInfoConstants.PASSENGER_GET_OFF);
        // 获取订单行驶的路程和时间
        ResponseResult<Car> carById = serviceDriverUserClient.getCarById(orderInfo.getCarId());
        Long starttime = orderInfo.getPickUpPassengerTime().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        Long endtime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println("开始时间："+starttime);
        System.out.println("结束时间："+endtime);
        ResponseResult<TrsearchResponse> trsearch = serviceMapClient.trsearch(carById.getData().getTid(), starttime,endtime);
        TrsearchResponse data = trsearch.getData();
        Long driveMile = data.getDriveMile();
        Long driveTime = data.getDriveTime();
        orderInfo.setDriveMile(driveMile);
        orderInfo.setDriveTime(driveTime);

        // 计算价格
        String address = orderInfo.getAddress();
        String vehicleType = orderInfo.getVehicleType();
        ResponseResult<Double> doubleResponseResult = servicePriceClient.calculatePrice(driveMile.intValue(), driveTime.intValue()*60, address, vehicleType);
        Double price = doubleResponseResult.getData();
        orderInfo.setPrice(price);

        orderInfoMapper.updateById(orderInfo);
        return ResponseResult.success();
    }

    /**
     * @Description: 根据 orderId 获取订单详情
     * @Param: [orderId]
     * @return: com.weayer.dto.ResponseResult<com.weayer.dto.OrderInfo>
     **/
    public ResponseResult<OrderInfo> detail(Long orderId){
        OrderInfo orderInfo =  orderInfoMapper.selectById(orderId);
        return ResponseResult.success(orderInfo);
    }

    /**
     * @Description: 根据 identity,phone 获取订单详情
     * @Param: [phone, identity]
     * @return: com.weayer.dto.ResponseResult<com.weayer.dto.OrderInfo>
     **/
    public ResponseResult<OrderInfo> current(String phone, String identity){
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();

        if (identity.equals(IdentityConstants.DRIVER_IDENTITY)){
            queryWrapper.eq("driver_phone",phone);

            queryWrapper.and(wrapper->wrapper
                    .eq("order_status",OrderInfoConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderInfoConstants.DRIVER_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderInfoConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderInfoConstants.PASSENGER_GET_ON)

            );
        }
        if (identity.equals(IdentityConstants.PASSENGER_IDENTITY)){
            queryWrapper.eq("passenger_phone",phone);
            queryWrapper.and(wrapper->wrapper.eq("order_status",OrderInfoConstants.ORDER_START)
                    .or().eq("order_status",OrderInfoConstants.DRIVER_RECEIVE_ORDER)
                    .or().eq("order_status",OrderInfoConstants.DRIVER_PICK_UP_PASSENGER)
                    .or().eq("order_status",OrderInfoConstants.DRIVER_ARRIVED_DEPARTURE)
                    .or().eq("order_status",OrderInfoConstants.PASSENGER_GET_ON)
                    .or().eq("order_status",OrderInfoConstants.PASSENGER_GET_OFF)
                    .or().eq("order_status",OrderInfoConstants.PAYING_START)
            );
        }

        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        return ResponseResult.success(orderInfo);
    }


}
